import { ForbiddenException, Injectable } from '@nestjs/common'
import { Model } from 'mongoose'
import { InjectModel } from '@nestjs/mongoose'
import { Table } from './schemas/table.schema'
import { randomUUID } from 'node:crypto'

@Injectable()
export class TableService {
  constructor(@InjectModel(Table.name) private tableModel: Model<Table>) {}

  async insertMany(tables: any[]): Promise<any[]> {
    for (const item of tables) {
      const table: any = item
      if (!table.id) table.id = randomUUID()
    }
    return this.tableModel.insertMany(tables)
  }

  async find(query: Record<string, any>): Promise<any> {
    const { currentPage, pageSize } = query
    const options: any = {
      sort: { _id: -1 }
    }

    if (currentPage) {
      options.skip = (currentPage - 1) * pageSize
      delete query.currentPage
    }

    if (pageSize) {
      options.limit = +pageSize
      delete query.pageSize
    }

    const total = await this.tableModel.countDocuments(query).exec()
    const data = await this.tableModel.find(query, null, options).exec()

    return {
      total: total,
      data: data
    }
  }

  async deleteOne(data: any) {
    return await this.tableModel.deleteOne(data).exec()
  }
}
